package com.lexin.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/***
 * Bean的工具
 * @author Lexin
 */
public class BeanUtil {
	
	/***
	 * 初始化Bean的数值型参数为指定的值
	 * @param obj
	 * @param numArg
	 */
	public static Object initBeanNumberArgs(Object obj, Integer numArg) {
		Class<?> objClass = obj.getClass();
		Field[] fields = objClass.getDeclaredFields();
		try {
			String fieldName = null;
			for (Field field : fields) {
				if (isNumberType(field.getType())==true) {
					fieldName = field.getName();
					fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 
						Method method = objClass.getDeclaredMethod("set" + fieldName , field.getType());
						method.invoke(obj, numArg);
				}
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	/***
	 * 获取Bean的Map形式（变量名：变量值）
	 * @param obj
	 * @return
	 */
	public static Map<String,Object> getBeanMap(Object obj) {
		Map<String, Object> map = new HashMap<String, Object>();
		Class<?> objClass = obj.getClass();
		Field[] fields = objClass.getDeclaredFields();
		try {
			String fieldName = null;
			String methodName = null;
			for (Field field : fields) {
				fieldName = field.getName();
				methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 
				Method method = objClass.getDeclaredMethod(methodName);
				map.put(fieldName, method.invoke(obj));
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/***
	 * 获取Bean的字段名
	 * @param obj
	 * @return
	 */
	public static String getFieldName(Object obj, String name) {
		String res = null;
		try {
			res = obj.getClass().getField(name).getName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	/***
	 * 封装表单内容成指定的Bean
	 * @param request
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Object formBean(HttpServletRequest request, Class<?> obj) throws Exception {
		Object object = null;
		if (obj != null) {
			Field[] field = obj.getDeclaredFields();
			object = obj.newInstance();
			for (int i = 1; i <field.length ; i++) {
				String name = field[i].getName();
				Object value = request.getParameter(name);
				if ((value==null || value.equals(""))==false) {
					name = name.substring(0, 1).toUpperCase() + name.substring(1); 
					Method method = obj.getDeclaredMethod("set" + name , field[i].getType());
					if (field[i].getType().equals(String.class)==true) {
						method.invoke(object, value.toString());
					} else if (field[i].getType().equals(Integer.class)==true) {
						method.invoke(object, Integer.parseInt(value.toString()));
					} else if (field[i].getType().equals(Long.class)==true) {
						method.invoke(object, Long.parseLong(value.toString()));
					} else if (field[i].getType().equals(Boolean.class)==true) {
						method.invoke(object, Boolean.parseBoolean(value.toString()));
					} else if (field[i].getType().equals(Double.class)==true) {
						method.invoke(object, Double.parseDouble(value.toString()));
					} else if (field[i].getType().equals(Float.class)==true) {
						method.invoke(object, Float.parseFloat(value.toString()));
					} else if (field[i].getType().equals(Byte.class)==true) {
						method.invoke(object, Byte.parseByte(value.toString()));
					} else if (field[i].getType().equals(Character.class)==true) {
						method.invoke(object, value.toString().charAt(0));
					} else if (field[i].getType().equals(Short.class)==true) {
						method.invoke(object, Short.parseShort(value.toString()));
					}
				} else {
					name = name.substring(0, 1).toUpperCase() + name.substring(1); 
					Method method = obj.getDeclaredMethod("set" + name , field[i].getType());
					if (field[i].getGenericType().getTypeName().toUpperCase().indexOf("INTEGER")>-1) {
						method.invoke(object, -1);
					} else if (field[i].getGenericType().getTypeName().toUpperCase().indexOf("LONG")>-1) {
						method.invoke(object, -1);
					}  else if (field[i].getGenericType().getTypeName().toUpperCase().indexOf("INT")>-1) {
						method.invoke(object, -1);
					} else if (field[i].getGenericType().getTypeName().toUpperCase().indexOf("DOUBLE")>-1) {
						method.invoke(object, -1);
					} else if (field[i].getGenericType().getTypeName().toUpperCase().indexOf("FLOAT")>-1) {
						method.invoke(object, -1);
					} else if (field[i].getGenericType().getTypeName().toUpperCase().indexOf("BYTE")>-1) {
						method.invoke(object, -1);
					} else if (field[i].getGenericType().getTypeName().toUpperCase().indexOf("SHORT")>-1) {
						method.invoke(object, -1);
					}
				}
			}
		}
		return object;
	}
	
//	public static void main(String[] args) {
//		Sequence seq = new Sequence();
//		Map<String, Object> map = BeanUtil.getBeanMap(seq);
//		for (String key : map.keySet()) {
//			System.out.println(key+"--"+map.get(key));
//		}
//	}
	
	/** 
	 * @param targetClazz java.lang.reflect.Field 的数据类型 clazz。 getType 方法获取
	 * @return
	 */
	public static boolean isNumberType(Class<?> targetClazz) {
	    // 判断包装类
	    if (Number.class.isAssignableFrom(targetClazz)) {
	        return true;
	    }
	    // 判断原始类,过滤掉特殊的基本类型
	    if (targetClazz == boolean.class || targetClazz == char.class || targetClazz == void.class) {
	        return false;
	    }
	    return targetClazz.isPrimitive();
	}
	
}
